package com.yzg.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author misterWei
 * @create 2020年05月15号:23点44分
 * @mailbox forcontinue@163.com
 * 多条件变量
 */
@Slf4j(topic = "c.condition")
public class LockCondition {
     static  ReentrantLock ROOM = new ReentrantLock();
    /**
     * 声明出两个条件变量
     */
    static Condition condition1 = ROOM.newCondition();
     static Condition condition2 = ROOM.newCondition();
     //条件依据
    static volatile boolean flag1 = false;
    static volatile boolean flag2 = false;
    public static void main(String[] args) throws InterruptedException {
        new Thread(()->{
            ROOM.lock();
            try {
              while (!flag1){
                  try {
                      log.error("t1 条件不符正在等待获取食物!");
                      condition1.await();
                      log.error("t1 获取食物!");
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }
              }

            }finally {
                ROOM.unlock();
            }
        },"t1").start();

        new Thread(()->{
            ROOM.lock();
            try {
                while (!flag2){
                    try {
                        log.error("t2 条件不符正在等待抽烟!");
                        condition2.await();
                        log.error("t2 获取抽烟!");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }finally {
                ROOM.unlock();
            }
        },"t2").start();

        TimeUnit.SECONDS.sleep(2L);
        new Thread(()->{
            ROOM.lock();
            try {
                //开始送烟送食物
                condition1.signal();
                flag1 = true;
                condition2.signal();
                flag2 = true;
            }finally {
                ROOM.unlock();
            }

        },"cron").start();
    }

}
